package com.zhuliwei.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.entity.Article;
import com.zhuliwei.mapper.ArticleMapper;
import com.zhuliwei.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目启动给Redis更新浏览量
 *
 * @author 朱力维
 * @time 2022/10/19 11:25
 **/
@Component
public class ArticleRunner implements CommandLineRunner {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //  从数据库查询文章数据
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper();
        lqw.select(Article::getId,Article::getViewCount);
        List<Article> articles = articleMapper.selectList(lqw);
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(Article::getId, article -> article.getViewCount().intValue()));
        // 存浏览量储到redis中
        redisCache.setCacheMap(SystemConstants.VIEWCOUNT_MAP_PREFIX,viewCountMap);
    }
}
